import React, { useState, useMemo } from "react";
// useMemo也是用来缓存函数的，语法和useCallback完全相同
// 类似于vue的计算属性

// useCallback和useMemo的区别
// useCallback缓存的是函数本身
// useMemo缓存的是函数的返回值

const App = () => {
  const [count, setCount] = useState(1);
  const [num, setNum] = useState(1);

  const [list] = useState([1, 2, 3, 4, 5, 6, 7]);

  const sum = useMemo(() => {
    console.log("sum被执行了");
    let s = 0;
    for (let i = 0; i < 100 * count; i++) {
      s += i;
    }
    return s;
  }, [count]);

  const oddList = useMemo(() => {
    return list.filter((item) => item % 2);
  }, [list]);

  return (
    <>
      <h2>useMemo</h2>
      <p>{count}</p>
      <button onClick={() => setCount((v) => v + 1)}>+</button>
      <p>{sum}</p>

      <hr />

      <p>{num}</p>
      <button onClick={() => setNum((v) => v + 1)}>+</button>

      <hr />

      <ul>
        {oddList.map((item) => (
          <li key={item}>{item}</li>
        ))}
      </ul>
    </>
  );
};

export default App;
